package com.xymtop.api.interceptor;

import com.xymtop.api.config.Premission;
import com.xymtop.api.implement.UserImpl;
import com.xymtop.api.service.UserService;
import com.xymtop.api.utils.MyCookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName : AdminInterCeptor
 * @Description : 管理员拦截器
 * @Author : 肖叶茂
 * @Date: 2022/12/4  16:08
 */
public class AdminInterCeptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String userid =MyCookie.getCookie(request,"userid");
        String code =MyCookie.getCookie(request,"code");

        if (userid!=null && code!=null && code.equals(Premission.ADMIN)){ //说明此时已登录并且是管理员
            return true;
        }else{ //说明未登录
            //重定向至登录页面
//            response.sendRedirect("/");
            response.setHeader("Content-Type", "application/json;charset=UTF-8");//注意加上这一句
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            response.getWriter().write("{\n" +
                    "    \"status\": 500,\n" +
                    "    \"message\": \"没有登录或者不是管理员\",\n" +
                    "    \"data\": null\n" +
                    "}");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
